﻿using Cms.Application.WebFramework.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.WebFramework.Presenters
{
    public class PagePresenter : BasePresenter
    {
        private readonly Page _page;
        private readonly IPageView _view;
        
        public PagePresenter(IPageView view)
            : this(view, new RepositoryFactory())
        {
        }

        public PagePresenter(IPageView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;

            // Re-fetch the page object, now with the complete graph
            _page = PageRepository.GetPageFromFrontEnd(_view.PageID);

            // Override user access control if logged in as administrator
            if (_view.AdministratorID > 0)
            {
                return;
            }
            if (_page == null)
            {
                return;
            }
            if (_page.GetRequiredUserGroups().Count > 0)
            {
                // Check if a user is already logged in. If not, redirect to the login page of the first UserGroup found
                User user = UserRepository.GetUser(_view.UserID);
                if (user == null)
                {
                    RedirectUserToLoginPage(_page.GetRequiredUserGroups()[0].GetLoginPageUrl());
                    return;
                }

                // Check if the user has access to any of the UserGroups required
                bool authorized = false;
                foreach (Membership membership in user.Memberships)
                {
                    if (_page.GetRequiredUserGroups().Contains(membership.UserGroup) && membership.IsActive())
                    {
                        authorized = true;
                        break;
                    }
                }
                if (!authorized)
                {
                    RedirectUserToLoginPage(_page.GetRequiredUserGroups()[0].GetLoginPageUrl());
                    return;
                }
            }
            //_page.Hits++;
            //PageRepository.SavePage(_page);
        }

        private void RedirectUserToLoginPage(string loginPageUrl)
        {
            if (loginPageUrl.ToLower() == "/" + _page.GetVirtualPath().ToLower())
                return;
            _view.RedirectUserToLoginPage(loginPageUrl);
        }

        public void LogVisitedPublicUrl(string queryString)
        {
            Administrator _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            _administrator.LogVisitedPublicUrl(_page, queryString);
            AdministratorRepository.SaveAdministrator(_administrator);
        }
    }
}